<template>
  <el-container style="height: 950px; border: 1px solid #eee">
    <el-main>
      <router-view/>
      <el-row :gutter="40">
        <el-col class="dayEL" :span="17">
          <el-card class="box-card">
            <el-calendar >
              <template #dateCell="{data}" >
                <el-badge :value="getCountByDay1(data.date)" style="float: left;" type="success" :hidden="hideLogic(data.date)"></el-badge>
                <el-badge :value="getCountByDay2(data.date)" style="float: right;" :hidden="hideLogic2(data.date)"></el-badge>
                <p class="spandate" @click="clickEvent(data.date)">
                  {{data.date.getDate()}}
                </p>
              </template>
            </el-calendar>
          </el-card>
        </el-col>
        <el-col :span="7">
          <el-card class="box-card">
            <el-tabs v-model="activeName" @tab-click="">
              <el-tab-pane label="咨询师" name="consultant">
                <el-menu text-color="#000" >
                  <el-menu-item @click="dialogVisible=true">
                    <template #title><i class="el-icon-plus"></i>添加排班</template>
                  </el-menu-item>
                </el-menu>
                <el-table :show-header="false" :data="dataList.slice((currentPage1-1)*pageSize1,currentPage1*pageSize1)"
                          height="645px">
                  <el-table-column prop="id" v-if="false"></el-table-column>
                  <el-table-column prop="duty" v-if="false"></el-table-column>
                  <el-table-column prop="name"></el-table-column>
                  <el-table-column prop="url">
                    <template #default="scope" >
                      <el-avatar :src="scope.row.url"></el-avatar>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" align="center">
                    <template #default="scope">
                      <el-button type="danger" icon="el-icon-delete" @click.prevent="handleDelete(scope.row,scope.$index,dataList)" circle></el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <el-pagination
                    background
                    layout="prev, pager, next"
                    :current-page="currentPage1"
                    :total="dataList.length"
                    :page-size="pageSize1"
                    @current-change="paging1"
                >
                </el-pagination>
              </el-tab-pane>
              <el-tab-pane label="督导" name="mentor">
                <el-menu text-color="#000">
                  <el-menu-item @click="dialogVisible=true">
                    <template #title><i class="el-icon-plus"></i>添加排班</template>
                  </el-menu-item>
                </el-menu>
                <el-table :show-header="false" :data="dataList2.slice((currentPage2-1)*pageSize2,currentPage2*pageSize2)"
                          height="645px">
                  <el-table-column prop="id" v-if="false"></el-table-column>
                  <el-table-column prop="name"></el-table-column>
                  <el-table-column prop="url">
                    <template #default="scope" >
                      <el-avatar :src="scope.row.url"></el-avatar>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" align="center">
                    <template #default="scope">
                      <el-button type="danger" icon="el-icon-delete" @click.prevent="handleDelete(scope.row,scope.$index,dataList2)" circle></el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <el-pagination
                    background
                    layout="prev, pager, next"
                    :current-page="currentPage2"
                    :total="dataList2.length"
                    :page-size="pageSize2"
                    @current-change="paging2"
                >
                </el-pagination>
              </el-tab-pane>

            </el-tabs>
          </el-card>
        </el-col>
      </el-row>
      <el-dialog
          title="请填写"
          v-model="dialogVisible"
          width="30%"
          :before-close="handleClose"
      >
        <el-form :model="form" >
          <el-form-item label="姓名" :label-width="120">
            <el-select v-model="form.id" filterable placeholder="请选择">
              <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="排班日期" :label-width="120">
            <el-date-picker
                v-model="form.date"
                type="date"
                placeholder="选择日期"
                :value-format=valueFormat :format=format
                style="width: 220px"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="danger" @click="dialogVisible=false">取消</el-button>
            <el-button type="primary" @click="handleAdd(form)">添加</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </el-main>
  </el-container>
</template>

<script>
const circleUrl = 'https://images.996pic.com/7021030b0ad843b9ab92571845d88fd1680_680.jpg'
export default {
  name: "AdminDuty",
  data(){
    return{
      monthStat:0,
      yearStat:2022,
      currentPage1:1,
      pageSize1:8,
      currentPage2:1,
      pageSize2:8,
      options: [
        {
          value: 'qwx',
          label: 'qwx',
        },
        {
          value: 'qwy',
          label: 'qwy',
        },
        {
          value: 'qwz',
          label: 'qwz',
        },
        {
          value: 'abc',
          label: 'abc',
        },
        {
          value: 'asd',
          label: 'asd',
        },
      ],

      dialogVisible:false,
      activeName: 'consultant',
      form:{
        id:'',
        date:'', //上班日期
      },
      valueFormat:'YYYY-MM-DD',
      format:'YYYY-MM-DD',
      activeday:[ //临时处理，在后端接口完成后接上
        {date:'03-01',count1:19,count2:2},//count1代表咨询师数量 count2代表督导数量
      ],
      dataList:[

      ],
      dataList2:[

      ],
      nowdate:new Date(),
    }
  },
  methods:{
    clickEvent(date){
      const _this = this
      let dateYear = date.getFullYear()
      let dateMonth = (1+date.getMonth())
      let dateDay =  date.getDate()
      console.log(dateYear)
      console.log(dateMonth)
      console.log(dateDay)
      _this.$axios.get('http://106.14.247.163:8080/duty/getDutyByDay/'+dateYear+'/'+dateMonth+'/'+dateDay).then(resp=>{
        let res1 = resp.data.data.consultants
        let res2 = resp.data.data.supervisors
        _this.dataList=[]
        _this.dataList2=[]
        for (let item of res1){
          _this.dataList.push({
            // name:item.userInfo.userName,
            // id:item.userInfo.userId,
            name:item.info.userInfo.userName,
            id:item.info.userInfo.userId,
            duty:item.dutyId,
            url:circleUrl
          })
        }
        for (let item of res2){
          _this.dataList2.push({
            // name:item.userInfo.userName,
            // id:item.userInfo.userId,
            name:item.info.userInfo.userName,
            id:item.info.userInfo.userId,
            duty:item.dutyId,
            url:circleUrl
          })
        }
      })

    },
    paging1(val){
      const _this = this
      _this.currentPage1 = val
    },
    paging2(val){
      const _this = this
      _this.currentPage2 = val
    },
    handleClick(tab, event) {
      console.log(tab, event)
    },
    handleAdd(form){
      this.$confirm('确认添加？')
          .then(async (_) => {
            const _this = this

            if (form.date===''||form.date===null||form.date===undefined||form.id===''||form.id===null||form.id===undefined){
              _this.$message.error('请检查输入项')
            }else{
              let p = form.date.split('-')
              let idList1 = []
              let idList2 = []
              await _this.$axios.get('http://106.14.247.163:8080/duty/getDutyByDay/' + p[0] + '/' + p[1] + '/' + p[2]).then(resp => {
                for (let item of resp.data.data.consultants) {
                  idList1.push(item.info.userInfo.userId)
                }
                for (let item of resp.data.data.supervisors) {
                  idList2.push(item.info.userInfo.userId)
                }
                if (idList1.includes(form.id) || idList2.includes(form.id)) {
                  _this.$message.error('您已为此人添加过排班!')
                } else {
                  _this.$message.success('添加成功')
                  _this.$axios.post('http://106.14.247.163:8080/duty/addDuty', {
                    date: form.date, userId: form.id
                  }).then(_ => {
                    _this.$message.success('添加成功')
                    _this.dialogVisible = false
                    _this.$router.go(0)
                  }).catch((err) => {
                    console.log(err)
                  })
                }
              })
            }
          })

    },
    handleDelete(row,index,data){
      this.$confirm('您确定要删除这趟排班？')
          .then((_) => {
            const _this = this
            _this.$axios.post('http://106.14.247.163:8080/duty/deleteDuty',{dutyId:row.duty,userId:row.id}).then(resp=>{
              console.log(resp)
            })
            data.splice(index,1)
            _this.$message.success('已删除！')
          })
          .catch((_) => {})

    },
    handleClose() {
      this.$confirm('确认关闭？')
          .then((_) => {
            const _this = this
            _this.dialogVisible = false
          })
          .catch((_) => {})
    },
    getCountByDay1(date){

      const _this = this
      if (date.getMonth()!== _this.monthStat-1){
        return 0;
      }
      if (date.getDate()>_this.activeday.length){return 0;}
      let count = _this.activeday[date.getDate()-1]['count1']
      return count
    },
    getCountByDay2(date){
      const _this = this
      if (date.getMonth()!==_this.monthStat-1){
        return 0;
      }
      if (date.getDate()>_this.activeday.length){return 0;}

      let count = _this.activeday[date.getDate()-1]['count2']
      return count
    },
    hideLogic(date){
      const _this = this
      if (_this.getCountByDay1(date)===0){
        return true
      }else{
        return false
      }
    },
    hideLogic2(date){
      const _this = this
      if (_this.getCountByDay2(date)===0){
        return true
      }else{
        return false
      }
    },


  },
  async created() {
    const _this = this
    await _this.$axios.get('http://106.14.247.163:8080/consultant/getAllConsultants').then(resp=>{
      _this.options = []
      for (let item of resp.data.data){
        if (item.userInfo===null||item.userInfo.userId===null||item.userInfo.userName===null){continue}
        _this.options.push({
          value:item.userInfo.userId,
          label:item.userInfo.userName
        })
      }
    })
    await _this.$axios.get('http://106.14.247.163:8080/supervisor/getAllSupervisors').then(resp=>{
      for (let item of resp.data.data){
        if (item.userInfo===null||item.userInfo.userId===null||item.userInfo.userName===null){continue}
        _this.options.push({
          value:item.userInfo.userId,
          label:item.userInfo.userName
        })
      }
    })
    let now = new Date()
    let year = now.getFullYear()
    console.log(year)
    let month = now.getMonth()+1
    _this.monthStat = month
    console.log(month)
    //求一个月有几天 即求下月的0号是几号 如5月0日，即4月最后一日
    now.setMonth(month)
    now.setDate(0)
    console.log(now)
    let MonthDays = now.getDate()
    console.log(MonthDays)
    await _this.$axios.get('http://106.14.247.163:8080/duty/getDutySummary/'+year+'/'+month).then(resp=>{
      _this.activeday = []
      let item = resp.data.data
      for (let i = 1; i <= MonthDays; i++) {
        _this.activeday.push({date:month+'-'+i,count1:item['day'+i].consultantCount,count2:item['day'+i].supervisorCount})
      }
    }).catch(err=>{
      console.warn(err)
    })
    let nowDay = new Date()
    let dateYear = nowDay.getFullYear()
    let dateMonth = (1+nowDay.getMonth())
    let dateDay =  nowDay.getDate()
    await _this.$axios.get('http://106.14.247.163:8080/duty/getDutyByDay/'+dateYear+'/'+dateMonth+'/'+dateDay).then(resp=>{
      let res1 = resp.data.data.consultants
      let res2 = resp.data.data.supervisors
      _this.dataList=[]
      _this.dataList2=[]
      for (let item of res1){
        _this.dataList.push({
          name:item.info.userInfo.userName,
          id:item.info.userInfo.userId,
          duty:item.dutyId,
          url:circleUrl
        })
      }
      for (let item of res2){
        _this.dataList2.push({
          name:item.info.userInfo.userName,
          id:item.info.userInfo.userId,
          duty:item.dutyId,
          url:circleUrl
        })
      }
    })
    await _this.$nextTick(() => {
      // 点击上个月
      let prevBtn1 = document.querySelector('.el-calendar__button-group .el-button-group>button:nth-child(1)');
      prevBtn1.addEventListener('click', () => {
        if (_this.monthStat===1){
          _this.monthStat = 12
          _this.yearStat--
        }else {
          _this.monthStat--
        }
        _this.$axios.get('http://106.14.247.163:8080/duty/getDutySummary/' + _this.yearStat + '/' + _this.monthStat).then(resp => {
          _this.activeday = []
          let item = resp.data.data
          for (let i = 1; i <= MonthDays; i++) {
            _this.activeday.push({
              date: month + '-' + i,
              count1: item['day' + i].consultantCount,
              count2: item['day' + i].supervisorCount
            })
          }
        }).catch(err => {
          console.warn(err)
        })
      })
      // 点击今天
      let prevBtn2 = document.querySelector('.el-calendar__button-group .el-button-group>button:nth-child(2)');
      prevBtn2.addEventListener('click', () => {
        let date = new Date()
        let dateYear = date.getFullYear()
        let dateMonth = (1+date.getMonth())
        let dateDay =  date.getDate()
        _this.yearStat = dateYear
        _this.monthStat = dateMonth
        _this.$axios.get('http://106.14.247.163:8080/duty/getDutyByDay/'+dateYear+'/'+dateMonth+'/'+dateDay).then(resp=>{
          let res1 = resp.data.data.consultants
          let res2 = resp.data.data.supervisors
          _this.dataList=[]
          _this.dataList2=[]
          for (let item of res1){
            _this.dataList.push({
              name:item.info.userInfo.userName,
              id:item.info.userInfo.userId,
              duty:item.dutyId,
              url:circleUrl
            })
          }
          for (let item of res2){
            _this.dataList2.push({
              name:item.info.userInfo.userName,
              id:item.info.userInfo.userId,
              duty:item.dutyId,
              url:circleUrl
            })
          }
        })
      })
      // 点击下个月
      let prevBtn3 = document.querySelector('.el-calendar__button-group .el-button-group>button:nth-child(3)');
      prevBtn3.addEventListener('click', () => {
        if (_this.monthStat===12){
          _this.monthStat = 1
          _this.yearStat++
        }else{
          _this.monthStat++
        }
        _this.$axios.get('http://106.14.247.163:8080/duty/getDutySummary/' + _this.yearStat + '/' + _this.monthStat).then(resp => {
          _this.activeday = []
          let item = resp.data.data
          for (let i = 1; i <= MonthDays; i++) {
            _this.activeday.push({
              date: month + '-' + i,
              count1: item['day' + i].consultantCount,
              count2: item['day' + i].supervisorCount
            })
          }
        }).catch(err => {
          console.warn(err)
        })
      })
    })

  }

}
</script>

<style lang="scss" scoped>
.dayEL .el-button--small {
  border: none;
}
.dayEL .el-button {
  background: transparent;
}

.spandate {
  margin-top: 10px;
  position: relative;
  top: 20px;
  font-weight: bold;
  font-size: 16px;
}

</style>
<style lang="css" scoped>
  .box-card /deep/ .el-calendar-table .el-calendar-day{
    height: 100px;
  }
</style>